<template>
	<view>
		<view class="uni-header">
			<view class="uni-group hide-on-phone">
				<view class="uni-title">{{$t('demo.table.title')}}</view>
			</view>
			<view class="uni-group">
				<!-- 输入框 -->
				<input class="uni-search" type="text" v-model="searchVal" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<!-- 搜索按钮 -->
				<button class="uni-button" type="default" size="mini"
					@click="search">{{$t('common.button.search')}}</button>
				<!-- 添加按钮 -->
				<button v-if="$power('addRoles')" class="uni-button" type="primary" size="mini"
					@click="add()">{{$t('common.button.add')}}</button>
				<!-- 批量删除按钮 -->
				<!-- <button class="uni-button" type="warn" size="mini"
					@click="delTable">{{$t('common.button.batchDelete')}}</button> -->
			</view>
		</view>
		<view class="uni-container">
			<!-- 表格组件 -->
			<uni-table :loading="loading" border stripe type="selection" :emptyText="$t('common.empty')"
				@selection-change="selectionChange">
				<uni-tr>
					<!-- 表头列  width="150" width="60" width="80" width="204"-->
					<uni-th align="center">角色名称</uni-th>
					<uni-th align="center">路由权限</uni-th>
					<uni-th align="center">接口权限</uni-th>
					<uni-th align="center">角色描述</uni-th>
					<uni-th width="200" align="center">设置</uni-th>
				</uni-tr>
				<uni-tr v-for="(item ,index) in tableData" :key="index">
					<!-- 表格数据列 -->
					<uni-td>{{item.roleName}}</uni-td>
					<uni-td>
						<el-row justify="start">
							<view v-for="(ite,inde) in permitList" :key="inde" style="margin-right: 20rpx;">
								<el-tag
									v-if="item.authIds && Array.isArray(item.authIds) && item.authIds.includes(ite.id)"
									type="primary">{{ite.text}}
								</el-tag>
							</view>
						</el-row>
					</uni-td>
					<uni-td>
						<el-row justify="start">
							<view v-for="(ite,inde) in powerList" :key="inde" style="margin-right: 20rpx;">
								<el-tag
									v-if="item.powerIds && Array.isArray(item.powerIds) && item.powerIds.includes(ite.id)"
									type="primary">{{ite.name}}
								</el-tag>
							</view>
						</el-row>
					</uni-td>
					<!-- <uni-td>
						<el-switch @change="updateUserState(item)" :disabled="!$power('updateUserState')" inline-prompt
							v-model="item.state" active-text="是" inactive-text="否" />
					</uni-td> -->
					<uni-td>
						<view class="name">{{item.roleDesc}}</view>
					</uni-td>
					<uni-td>
						<view class="uni-group">
							<!-- 编辑按钮 -->
							<button v-if="$power('updateRoles')" class="uni-button" @click="edit(item)" size="mini"
								type="primary">{{$t('common.button.edit')}}</button>
							<!-- 删除按钮 -->
							<button class="uni-button" size="mini" type="warn">{{$t('common.button.delete')}}</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<el-dialog v-model="dialogTableVisible" :title="$t('common.button.edit')+'_用户名：'+username" width="800">
				<el-form :model="form">
					<el-form-item label="角色名称: ">
						<el-input v-model="form.roleName" />
					</el-form-item>
					<el-form-item label="路由权限">
						<el-checkbox v-model="checkAllPermit" :indeterminate="isIndeterminatePermit"
							@change="permitCheckAllChange">
							所有路由权限
						</el-checkbox>
						<el-checkbox-group v-model="form.authIds" @change="permitCheckedChange">
							<el-checkbox v-for="permit in permitList" :key="permit.id" :label="permit.id"
								:value="permit.id">
								{{ permit.text }}
							</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="接口权限">
						<!-- <el-checkbox v-model="checkAllPower" :indeterminate="isIndeterminatePower"
							@change="powerCheckAllChange">
							所有路由权限
						</el-checkbox> -->
						<el-checkbox-group v-model="form.powerIds" style="display: flex;flex-wrap: wrap;">
							<view v-for="power in powerList" :key="power.id" style="margin-right: 55rpx;">
								<el-checkbox v-if="power.name=='所有权限管理'" @change="powerCheckAllChange" :label="power.id"
									:value="power.id">
									{{ power.name }}
								</el-checkbox>
								<el-checkbox v-else :disabled="isAllPower" :label="power.id" :value="power.id">
									{{ power.name }}
								</el-checkbox>
							</view>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="角色描述: ">
						<el-input v-model="form.roleDesc" type="textarea" />
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<!-- v-if="$hasPower('addUserBalance')" -->
						<el-button @click="dialogTableVisible = false">{{$t('common.button.cancel')}}</el-button>
						<el-button type="primary" @click="submit()">
							<!-- Confirm -->
							{{$t('common.button.submit')}}
						</el-button>
					</div>
				</template>
			</el-dialog>
			<view class="uni-pagination-box">
				<!-- 分页组件 -->
				<uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
					@change="change" />
			</view>
		</view>
		<!-- #ifndef H5 -->
		<fix-window />
		<!-- #endif -->
	</view>
</template>


<script>
	// 导入名为 "tableData" 的模块，路径为 './tableData.js'
	import tableData from './tableData.js'
	import {
		getRolesList,
		addUserBalance,
		updateUserBalance,
		updateUserState,
		getPermitList,
		getPowerList,
		updateRoles,
		addRoles
	} from '@/api/account';
	import {
		Check,
		Close
	} from '@element-plus/icons-vue'
	// 导出默认模块
	export default {
		// 数据属性
		data() {
			return {
				// 搜索值
				searchVal: '',
				// 表格数据
				tableData: [], //rolesList
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				// 加载状态
				loading: false,
				// ------- 新 ---------
				dialogTableVisible: false,
				balance: 0,
				username: '',
				type: '',
				form: {
					id: '',
					powerIds: [],
					authIds: [],
					roleName: '',
					roleDesc: ''
				},
				// 多选
				permitList: [],
				checkAllPermit: false,
				isIndeterminatePermit: false,
				powerList: [],
				isAllPower: false,
				checkAllPower: false,
				isIndeterminatePower: false,
			}
		},
		// 页面加载时的处理函数
		onLoad() {
			// 重置选中项数组
			this.selectedIndexs = []
			// 获取第一页数据
			this.getData(1)
			this.getPermitList()
			this.getPowerList()
		},

		// 方法
		methods: {
			// 多选处理
			selectedItems() {
				return this.selectedIndexs.map(i => this.tableData[i])
			},

			// 多选事件处理函数
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},

			// 批量删除函数
			delTable() {
				this.selectedItems();
			},

			// 分页触发事件处理函数
			change(e) {
				this.getData(e.current)
			},
			add() {
				this.form.id = '';
				this.form.authIds = [];
				this.form.powerIds = [];
				this.form.roleDesc = '';
				this.form.roleName = '';
				this.type = 'add';
				this.powerCheckAllChange(false)
				this.dialogTableVisible = true;
			},
			edit(e) {
				this.form.id = e._id;
				this.form.authIds = e.authIds;
				this.form.powerIds = e.powerIds;
				this.form.roleDesc = e.roleDesc;
				this.form.roleName = e.roleName;
				this.type = 'edit';
				if (e.powerIds && e.powerIds.includes(1)) {
					this.powerCheckAllChange(true)
				} else {
					this.powerCheckAllChange(false)
				}
				this.dialogTableVisible = true;
			},
			// 搜索函数
			search() {
				this.getData(1, this.searchVal)
			},
			submit() {
				var that = this;
				if (this.type == 'edit') {
					updateRoles(this.form).then(res => {
						if (res.code == 200) {
							that.$message.success(res.msg);
							that.getData(this.pageCurrent)
							that.dialogTableVisible = false;
						} else {
							that.$message.error(res.msg);
						}
					})
				} else {
					addRoles(this.form).then(res => {
						if (res.code == 200) {
							that.$message.success(res.msg);
							that.getData(this.pageCurrent)
							that.dialogTableVisible = false;
						} else {
							that.$message.error(res.msg);
						}
					})
				}
			},
			updateUserState(e) {
				var that = this;
				// console.log(e, e.state); 
				updateUserState({
					id: e._id,
					state: e.state
				}).then(res => {
					if (res.code == 200) {
						that.$message.success(res.msg);
						that.getData(this.pageCurrent)
					} else {
						that.$message.error(res.msg);
						e.state = !e.state;
					}
				})
			},
			getPermitList() {
				getPermitList().then(res => {
					// console.log(res);
					if (res.code == 200) {
						this.permitList = res.data
					} else {
						this.$message.error(res.msg || '失败!');
						this.permitList = []
					}
				})
			},
			getPowerList() {
				getPowerList().then(res => {
					// console.log(res);
					if (res.code == 200) {
						var name = '所有权限管理';
						this.powerList = res.data
						// console.log(JSON.stringify(this.powerList));
					} else {
						this.$message.error(res.msg || '登录失败');
						this.powerList = []
					}
				})
			},
			// 获取数据函数
			getData(pageCurrent, key = "") {
				this.loading = true
				this.pageCurrent = pageCurrent
				getRolesList({
					pageSize: this.pageSize,
					pageCurrent: pageCurrent,
					key: key,
				}).then(res => {
					// console.log(res);
					if (res.code == 200) {
						this.tableData = res.data
						this.total = res.total
						this.loading = false
					} else {
						this.$message.error(res.msg || '登录失败');
						this.tableData = []
						this.total = 0
						this.loading = false
					}
				})
			},
			// 多选
			permitCheckAllChange(val) {
				this.form.authIds = val ? this.permitList.map(item => {
					return item.id;
				}) : [];
				this.isIndeterminatePermit = false;
				console.log(JSON.stringify(this.form.authIds));
			},
			permitCheckedChange(value) {
				const checkedCount = value.length;
				this.checkAllPermit = checkedCount === this.permitList.length;
				this.isIndeterminatePermit = checkedCount > 0 && checkedCount < this.permitList.length;
				console.log(JSON.stringify(this.form.authIds));
			},
			// powerCheckAllChange(val) {
			// 	this.form.powerIds = val ? this.powerList.map(item => {
			// 		return item.id;
			// 	}) : [];
			// 	this.isIndeterminatePower = false;
			// 	console.log(JSON.stringify(this.form.powerIds));
			// },
			// powerCheckedChange(value) {
			// 	const checkedCount = value.length;
			// 	this.checkAllPower = checkedCount === this.powerList.length;
			// 	this.isIndeterminatePower = checkedCount > 0 && checkedCount < this.powerList.length;
			// 	console.log(JSON.stringify(this.form.powerIds));
			// },
			powerCheckAllChange(val) {
				this.isAllPower = val;
				// console.log(JSON.stringify(this.form.powerIds));
			},
			// 伪request请求函数
			request(options) {
				console.log(options);
				const {
					pageSize,
					pageCurrent,
					success,
					value
				} = options

				let total = tableData.length

				let data = tableData.filter((item, index) => {
					const idx = index - (pageCurrent - 1) * pageSize
					return idx < pageSize && idx >= 0
				})

				if (value) {
					data = []
					tableData.forEach(item => {
						if (item.name.indexOf(value) !== -1) {
							data.push(item)
						}
					})
					total = data.length
				}

				setTimeout(() => {
					typeof success === 'function' && success({
						data: data,
						total: total
					})
				}, 500)
			}
		}
	}
</script>


<style>
	/* #ifndef H5 */
	page {
		padding-top: 85px;
	}

	/* #endif */
</style>